package com.hmdp.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class RedisIdWorker {

    private static final long BEGIN_TIMESTAMP = 1744406223L;
    private static final int COUNT_BITS = 32;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成下一个ID
     * 该方法用于根据给定的键前缀生成一个唯一的ID该ID由时间戳和递增计数组成，
     * 以确保在相同的时间内生成的ID也是唯一的
     *
     * @param keyPrefix 键前缀，用于区分不同实体或用途的ID
     * @return 生成的唯一ID
     */
    public long nextrId(String keyPrefix) {
        // 获取当前时间戳
        long nowSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        // 计算相对于起始时间戳的偏移量
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 获取当前日期，格式为yyyyMMdd
        String nowDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 在Redis中递增计数器，计数器键由前缀、当前日期和固定前缀"icr:"组成
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" +  nowDate);

        // 将递增计数器左移COUNT_BITS位，然后与时间戳进行按位或操作，以生成最终的ID
        return count << COUNT_BITS | timestamp;
    }

//    public static void main(String[] args) {
//        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
//        long second = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
//        log.info("{}", second);
//
//    }

}
